using System.IO;
using System.Reflection;
using AutoTest.Core.Infrastructure.Messaging;
using log4net;

namespace AutoTest.Core.Domain.FileWatching
{
    public class FileWatcher : IFileWatcher
    {
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private readonly FileSystemWatcher _watcher;
        private readonly IAutoTestConfiguration _configuration;
        private readonly IMessageBus _messageBus;

        public FileWatcher(IAutoTestConfiguration configuration, IMessageBus messageBus)
        {
            _configuration = configuration;
            _messageBus = messageBus;
            _watcher = new FileSystemWatcher();
        }

        public void BeginWatching()
        {
            Logger.InfoFormat("Watching {0}...", _configuration.FolderToWatch);
            _watcher.NotifyFilter = NotifyFilters.LastWrite;
            _watcher.IncludeSubdirectories = true;
            _watcher.Filter = "*.cs";
            _watcher.Path = _configuration.FolderToWatch;
            _watcher.Changed += WatcherOnChanged;
            _watcher.Created += WatcherOnChanged;
            _watcher.EnableRaisingEvents = true;
        }

        private void WatcherOnChanged(object sender, FileSystemEventArgs e)
        {
            Logger.DebugFormat("Detected change in {0}", e.FullPath);
            _messageBus.Publish(this, new FileChangedMessage(new FileInfo(e.FullPath)));
        }
    }
}